//
//  WHYMainViewController.swift
//  WHYWeibo-1.0
//
//  Created by 王洪运 on 15/11/22.
//  Copyright © 2015年 王洪运. All rights reserved.
//

import UIKit

class WHYMainViewController: UITabBarController {
    


//    MARK: - 视图声明周期函数
    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
        setupComposedButton()

    }
    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        tabBar.bringSubviewToFront(composedButton)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
//    MARK: - 搭建撰写按钮
    private lazy var composedButton: UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
    
    private func setupComposedButton() {
        tabBar.addSubview(composedButton)
        
        let count = childViewControllers.count
        let marginW = tabBar.bounds.width / CGFloat(count) - 1
        
        composedButton.frame = CGRectInset(tabBar.bounds, marginW * 2, 0)
        
        composedButton.addTarget(self, action: "clickComposedButton", forControlEvents: .TouchUpInside)
        
    }
    
    @objc private func clickComposedButton() {
        let vc = WHYUserAccountViewModel.sharedUserAccount.userLogon ? WHYComposeViewController() : WHYOAuthViewController()
        let nav = UINavigationController(rootViewController: vc)
        
        presentViewController(nav, animated: true, completion: nil)
    }

}




// MARK: - 加载子控制器
extension WHYMainViewController {
    private func addChildViewControllers() {
        
        addChildViewController(WHYHomeViewController(), title: "首页", imageName: "tabbar_home")
        addChildViewController(WHYMessageViewController(), title: "消息", imageName: "tabbar_message_center")
        addChildViewController(UIViewController())
        addChildViewController(WHYDiscoverViewController(), title: "发现", imageName: "tabbar_discover")
        addChildViewController(WHYPorfileViewController(), title: "我", imageName: "tabbar_profile")
    }
    
    private func addChildViewController(viewController: UIViewController, title: String, imageName: String) {
        viewController.title = title
        
        viewController.tabBarItem.image = UIImage(named: imageName)
        
        let nav = UINavigationController(rootViewController: viewController)

        addChildViewController(nav)
    }
}

